import folium
import pandas as pd
from pandas import isnull
%store -r dfm
Before we create the map, we need to make sure the coordinates we will pass to the marker are either intergers or float (numbers not text). We also want to make sure there aren't any samples with strange coordinate values, like a longitude value greater than 180. And we also want to make sure we are only going to be looping over samples with location data.
dfm1 = dfm
dfm1["longitude"] = pd.to_numeric(dfm1["longitude"], downcast="float")
dfm1["latitude"] = pd.to_numeric(dfm1["latitude"], downcast="float")
for i, series in dfm1.iterrows():
if series.longitude > 180:
dfm1.drop(i, inplace=True)
dfmdropna = dfm1.dropna(subset=['latitude'])
Here you first need to declare the map as a variable. Then we can add the markers with tooltips and popovers in a classic iteration of the dataframe using a for loop. The arguments we are passing to folium.Marker are coordinates, as an array of longitude and latitude from our dataframe, tooltip and popover with whatever other data you want to display in those.
m = folium.Map()
for i, series in dfmdropna.iterrows():
folium.Marker([series.latitude, series.longitude],
tooltip=series.sample_name,
popup=(['Name:', series.sample_name, 'Title:', series.Title])).add_to(m)
m
With all of these samples the map can get lag a bit when you are moving it because there is just so much information on the screen. A way to combat this and speed up the app is to group all of the markers into clusters. Folium has a built in plugin called MarkerCluster that makes this very easy. Instead of directly adding the Marker to the map, we add them to a predifined variable that is a MarkerCluster(). After the Markers are added to the MarkerCluster we then add the MarkerCluster to the map.
from folium.plugins import MarkerCluster
c = folium.Map()
marker_cluster = folium.plugins.MarkerCluster()
for i, series in dfmdropna.iterrows():
marker_cluster.add_child(folium.Marker([series.latitude, series.longitude],
tooltip=series.sample_name,
popup=(['Name:', series.sample_name, 'Title:', series.Title])))
c.add_child(marker_cluster)